<template>
  <div class="app-container">
    <div class="search-box">
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="68px">
        <!-- <el-form-item label="店铺" prop="tenantId">
          <el-select v-model="queryParams.tenantId" placeholder="请选择店铺" clearable filterable>
            <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName"
                       :value="dict.tenantId"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="设备id" prop="machineId">
          <el-input v-model="queryParams.machineId" placeholder="请输入设备id" clearable />
        </el-form-item>
          <el-form-item label="容器名" prop="containerName">
          <el-input v-model="queryParams.containerName" placeholder="请输入容器名" clearable />
        </el-form-item>

        <el-form-item label="云机名称" prop="machineAlias">
          <el-input v-model="queryParams.machineAlias" placeholder="请输入云机名称" clearable />
        </el-form-item>

        <el-form-item label="类型" prop="machineType">
          <el-select v-model="queryParams.machineType" placeholder="请选择" clearable filterable>
            <el-option label="手机" value="1" />
            <el-option label="平板" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnable">
          <el-select v-model="queryParams.isEnable" placeholder="请选择" clearable filterable>
            <el-option label="启用" value="1" />
            <el-option label="关闭" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否远程" prop="machineType">
          <el-select v-model="queryParams.runStatus" placeholder="请选择" clearable filterable>
            <el-option label="是" value="2" />
            <el-option label="否" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" icon="el-icon-search" size="small" @click="search" class="zdy-btn">搜索
          </el-button>

          <el-button type="warning" plain icon="el-icon-refresh" size="small" @click="synchronize" class="zdy-btn">同步
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box table_box_new table-section" v-loading="loading">
      <el-table border :data="tableData.records" style="width: 100%">
        <el-table-column prop="machineId" label="设备id" width="320"></el-table-column>
        <el-table-column prop="containerName" sortable label="容器名" width="120"></el-table-column>
        <el-table-column prop="machineAlias" label="云机名称" width="120"></el-table-column>
        <el-table-column prop="machineGroup" label="云机分组" width="120">
          <template slot-scope="scope">
            <span>{{ getGroup(scope.row.machineGroup)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="accountCount" label="挂Q数量" width="120">
          <template slot-scope="scope">
            <span style="cursor: pointer;" @click="openQ(scope.row)">{{ scope.row.accountCount }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="tenantId" label="商家id"></el-table-column> -->
        <el-table-column prop="onlineStatus" label="状态" width="115">
          <template slot-scope="scope">
            <el-tag  v-if="scope.row.onlineStatus == 2">在线</el-tag>
             <el-tag type="success" v-if="scope.row.onlineStatus == 1">离线</el-tag>
              <el-tag type="danger" v-if="scope.row.onlineStatus == 3">异常</el-tag>
            <el-tag type="warning" v-if="scope.row.onlineStatus == 4">风险</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="machineType" label="类型" width="110">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.machineType == 1">手机</el-tag>
            <el-tag type="warning" v-else>平板</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="isEnable" label="是否启用" width="110">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.isEnable == 1">启用</el-tag>
            <el-tag type="warning" v-else>关闭</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="runStatus" label="是否远程" width="110">
          <template slot-scope="scope">
            <span style="color:rgb(64, 158, 255) ;" type="success" v-if="scope.row.runStatus == 2">是</span>
            <span style="color: rgb(230, 162, 60);" type="warning" v-else>否</span>
          </template>
        </el-table-column>

        <el-table-column prop="leaseStartTime" label="云机开始时间" width="180">
          <template slot-scope="scope">
            {{ parseTime(scope.row.leaseStartTime, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="leaseEndTime" label="云机到期时间">
          <template slot-scope="scope">
            {{ parseTime(scope.row.leaseEndTime, '{y}-{m}-{d}') }}
          </template>
        </el-table-column> -->

        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="text" @click="handleMakeClose(scope.row)">修改</el-button>
            <el-button type="text" @click="handleyunjiOpen(scope.row)">打开云机</el-button>
            <el-button type="text" @click="handleyunjiClose(scope.row)">关闭远程</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="pages-box">
      <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" @pagination="getList" />

    </div>
    <el-dialog title="修改云机" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="yunjiForm" label-width="80px">
        <el-form-item label="设备类型">
          <el-radio-group v-model="yunjiForm.machineType" class="margin-left-10">
            <el-radio :label="1">手机</el-radio>
            <el-radio :label="2">平板</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="yunjiForm.isEnable" active-color="#13ce66" :active-value="1" :inactive-value="2"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>

         <el-form-item label="云机分组">
          <el-select v-model="yunjiForm.machineGroup" placeholder="请选择" clearable filterable>
             <el-option v-for="dict in machineGroup" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancle">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看" :visible.sync="seeDialogVisible" width="75%">
      <div>
        <div class="table_box table_box_new table-section">
          <el-table border :data="qqTable.records" v-loading="loading" style="width: 100%">
            <el-table-column prop="tenantId" label="店铺id">
            </el-table-column>
            <el-table-column prop="tenantName" label="店铺名称">
            </el-table-column>
            <el-table-column prop="account" label="QQ账号">
            </el-table-column>
            <el-table-column prop="createdTime" label="添加时间" width="160">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.createdTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="添加时长">
              <template slot-scope="scope">
                <span class="duration-text">{{ getDay(scope.row.createdTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="loginTime" label="登录时间" width="160">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.loginTime) }}
              </template>
            </el-table-column>

            <el-table-column prop="loginTime" label="登录时长">
              <template slot-scope="scope">
                <span class="duration-text">{{ getDay(scope.row.loginTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="loginType" label="登录类型">
              <template slot-scope="scope">
                {{ scope.row.loginType === 2 ? 'QQ' : 'TIM' }}
              </template>
            </el-table-column>
            <el-table-column prop="onlineStatus" label="状态" align="center">
              <template slot-scope="scope">
                  <el-tag  v-if="scope.row.onlineStatus == 2">登录</el-tag>
             <el-tag type="success" v-if="scope.row.onlineStatus == 1">未登录</el-tag>
              <el-tag type="danger" v-if="scope.row.onlineStatus == 3">异常</el-tag>
            <el-tag type="warning" v-if="scope.row.onlineStatus == 4">风险</el-tag>
              
              </template>
            </el-table-column>
            <el-table-column prop="offlineTime" label="异常时间" width="160">
              <template slot-scope="scope">
                <span class="danger-text">{{ scope.row.offlineTime }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="checkPermi(['searchTenantID'])" prop="delFlag" label="是否删除" align="center">
              <template slot-scope="scope">
                {{ scope.row.delFlag === 2 ? '否' : '是' }}
              </template>
            </el-table-column>
            <el-table-column v-if="checkPermi(['searchTenantID'])" prop="cloudStatus" label="云端状态" align="center">
              <template slot-scope="scope">
                {{ scope.row.cloudStatus === 2 ? '删除' : '存在' }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button type="text" :disabled="scope.row.status === 1" @click="handleOpenAccount(scope.row)">
                打开账号
              </el-button>
              <el-button type="text" :disabled="scope.row.onlineStatus != 2" @click="openYunji(scope.row)">
                自动上号
              </el-button>
              <el-button type="text" class="danger-text" @click="handleDeleteAccount(scope.row)">
                删除
              </el-button>
              <el-button type="text" class="warning-text" @click="showStatus(scope.row)">
                刷新状态
              </el-button>
            </template>
          </el-table-column> -->
          </el-table>
        </div>
        <!-- 分页 -->
        <div class="pagination-section">
          <pagination v-show="qqTable.total > 0" :total="qqTable.total" :page.sync="qqData.pageNum"
            :limit.sync="qqData.pageSize" @pagination="getAllList" />
        </div>
      </div>
    </el-dialog>

    <el-dialog @close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false" title="远程云机"
      append-to-body :visible.sync="yunjiDialogVisible" width=" 400px">
      <div style="width: 334px;height: 620px;margin: auto;">
      <yunjiIframe v-if="wss_url" ref="yunjiIframeRef" :wssUrl="wss_url" :admin="admin"  />
        </div>
      <!-- <div class="footer">
        <el-button style="    font-size: 16px;
    height: 40px;
    width: 120px;" type="primary" :loading="submitLoading" @click="handleSubmit">
          确认登录
        </el-button>
      </div> -->
    </el-dialog>

  </div>

</template>
<script>
import { warehouseList, sync, adminClose, makeMachineExpire, update, getAllList ,yunjiVideo} from '@/api/tenantApis/cloudMachine'

import { getDicts } from "@/api/system/dict/data";

export default {
  components: {
    yunjiIframe: () => import('@/views/tenantPages/cloudMachine/components/yunjiIframe.vue'),

  },
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
  },
  data() {
    return {
      machineGroup:[],
      admin:true,
      yunjiDialogVisible:false,
      yunjiForm: {
        id: "",
        machineType: '',
        isEnable: '',
        machineGroup:''
      },
      bstateMap: [
        { label: '离线', value: 1 },
        { label: '在线', value: 2 }
      ],
      queryParams: {
        pageSize: 50,
        pageNum: 1
      },
      loading: false,
      tableData: {
        records: [],
        total: 0
      },
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // 'add' 或 'renew'
      selectedMachine: {},
      // 挂Q明细弹窗
      qDetailVisible: false,
      selectedQ: {},
      // 添加挂Q弹窗
      addQVisible: false,
      yudou: '',
      seeDialogVisible: false,
      qqData: {
        pageNum: 1,
        pageSize: 10,
        containerName: '',
      },
      qqTable: {
        records: [],
        total: 0,
      },
      tenant: {},
      wss_url:''
    }
  },
  created() {
      this.getYunji()
    this.getList()
    this.getMachine()
  },
  methods: {
    openQ(row) {
      this.qqData.containerName = row.containerName
      this.getAllList()
    },
    getAllList() {
      getAllList(this.qqData).then(res => {
        this.qqTable.records = res.rows
        this.qqTable.total = res.total
      }).finally(() => {
        this.seeDialogVisible = true
      });
    },

    handleMakeClose(row) {
    
      this.yunjiForm = {
        id: row.id,
        machineType: row.machineType,
        isEnable: row.isEnable,
        machineGroup: row.machineGroup
      }
      this.dialogVisible = true
    },
    // 强制关闭商户云机连接
    handleyunjiClose(row) {
      this.$modal.confirm('确定要强制关闭该云机连接吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminClose(row.id).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("操作成功")
            this.getList()
          }
        })
      })
    },
    handleCancle() {
      this.dialogVisible = false
      this.yunjiForm = {
        id: '',
        machineType: '',
        isEnable: '',
        machineGroup:''
      }
    },
    handleSubmit() {
      update(this.yunjiForm).then(res => {
        if (res.code == 200) {
          this.$modal.msgSuccess("操作成功")
          this.getList()
          this.handleCancle()
        }
      }).finally(() => {
        this.dialogVisible = false
      })
    },
    getMachine() {
      {
        getDicts('machine').then(res => {
          const foundItem = res.data.find(item => item.dictLabel === 'amount');
          if (foundItem) {
            this.yudou = foundItem.dictValue;
          }
        })
      }
    },
    getList() {
      warehouseList(this.queryParams).then(res => {
        this.tableData.records = res.rows;
        this.tableData.total = res.total;
      });
    },
    search() {
      this.getList()
    },
    synchronize() {
      sync().then(res => {
        this.$message.success(res.msg);
        this.getList();
      });
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    getDay(val) {
      if (!val) {
        return '---'
      }
      const now = new Date();
      const start = new Date(val);
      if (isNaN(start.getTime())) return '0天0小时';
      // 计算时间差（毫秒）
      const timeDiff = now.getTime() - start.getTime();
      if (timeDiff <= 0) return '0天0小时';
      const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      return `${days}天${hours}小时`;
    },

  async  handleyunjiOpen(row) {
    this.tenant = row
      const res = await yunjiVideo(row.machineId)
      this.wss_url = res.data.wss_url
      this.yunjiDialogVisible = true
    },
   async handleClose() {
    try{
      this.wss_url = ''
      // const res= await  adminClose(this.tenant.id)
      // if (res.code == 200) {
      //   this.getList()
      // }
    } catch(e) {
     
    }
    },
    getGroup(val) {
      if(!val) return '---'
      return this.machineGroup.find(item => item.dictValue === val).dictLabel
    },
     getYunji() {
      this.getDicts("machine_group").then((res) => {
        this.machineGroup = res.data
        
      });
    },
  },
};

</script>
<style lang="scss" scoped>
.titles-left-img {
  width: 190px;
  // height: 86px;
}

.titles-right-img {
  width: 200px;
}

.zdy-btn-rent {
  width: 120px;
  font-size: 16px;
  height: 40px;
}

.lines-img {
  margin-top: 2px;
  vertical-align: text-top;
  width: 18px;
  margin-left: 2px;
}
</style>
